<template>
    <basic-container>
        <h4 class="title">基本信息</h4>
        <el-form ref="customerForm"
            :model="customerOrder"
            label-width="120px"
            label-position="right">
            <el-row>
                <el-col :span="8">
                    <el-form-item label="业务员:">
                        <el-select 
                            filterable 
                            remote 
                            :remote-method="remoteStaffList" 
                            v-model="customerOrder.employeeId" 
                            placeholder="请选择">
                            <el-option v-for="item in teamList" :key="item.id" :label="item.name" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="客户名称:">
                        <select-customer-form 
                        :customerObj="{customerName: customerOrder.customerName, customerSn: customerOrder.customerSn}"
                        @changeCustomer="handleSelectCustomer"/>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="交货日期:">
                        <el-date-picker
                            class="fill-width"
                            :editable="false"
                            v-model="customerOrder.deliveryDate"
                            type="date"
                            placeholder="选择日期"
                            value-format="yyyy-MM-dd">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
            
            <el-row>
                <el-col :span="8">
                    <el-form-item label="销售单类型:">
                        <el-select
                            v-model="customerOrder.salesType"
                            placeholder="请选择">
                            <el-option key="1" label="代客下单" value="1">
                            </el-option>
                        <el-option key="2" label="自主下单" value="2">
                        </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="收货地址:">
                        <el-select
                            class="fill-width"
                            v-model="customerOrder.customerAddressId"
                            placeholder="请选择">
                            <el-option
                                v-for="item in addressList"
                                :key="item.id"
                                :label="item.address"
                                :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="备注:">
                        <el-input
                            class="fill-width"
                            type="textarea"
                            v-model="customerOrder.remarks"
                            placeholder="">
                        </el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="8">
                    <el-form-item label="其它金额:">
                        <el-input-number class="fill-width" v-model="customerOrder.otherAmount" style="float: left" placeholder="请输入" :precision="2" @change="countPrice"></el-input-number>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="商品合计金额:">
                        <el-input-number class="fill-width" :disabled="true" v-model="customerOrder.goodsTotalAmount" style="float: left" placeholder="请输入" :precision="2" @change="countPrice"></el-input-number>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="总计金额:">
                        <el-input-number class="fill-width" v-model="customerOrder.totalAmount" style="float: left" placeholder="请输入" :precision="2" @change="countCouponAmount"></el-input-number>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="8">
                    <el-form-item label="优惠金额:">
                        <el-input-number class="fill-width" :disabled="true" v-model="customerOrder.couponAmount" style="float: left" placeholder="请输入" :precision="2"></el-input-number>
                    </el-form-item>
                </el-col>
            </el-row>
            
            <el-row>
                <el-form-item>
                    <el-button type="primary" @click="resetForm">重置</el-button>
                </el-form-item>
            </el-row>
        </el-form>
        
        <div>
            <h4 class="title">普通商品列表</h4>
            <goods-record :type="1" :customerId="customerOrder.customerSn" v-on:addGoods="addGoods" v-on:goodsSubmit="goodsSubmit" />
            <goods-table :type="1" :goodsTable="orderList" :disabled="disabled" @change="changeTable"/>

            <h4 class="title m-t">赠品列表</h4>
            <goods-record :type="3" :customerId="customerOrder.customerSn" v-on:addGoods="addGoods" v-on:goodsSubmit="goodsSubmit" />
            <goods-table :type="3" :goodsTable="giftList" :disabled="disabled"/>

            <h4 class="title m-t">促销品列表</h4>
            <goods-record :type="2" :customerId="customerOrder.customerSn" v-on:addGoods="addGoods" v-on:goodsSubmit="goodsSubmit" />
            <goods-table :type="2" :goodsTable="promotionList" :disabled="disabled" @change="changeTable"/>
            
            <div style="margin-top: 30px; margin-bottom: 50px; text-align: center;">
                <el-button
                    type="primary"
                    @click="submitBuyOrder">提交订单
                </el-button>
            </div>

        </div>
    </basic-container>
</template>

<script>
    import Request from './../request.js';
    import rules from './rules.js';
    import goodsList from './components/goodsList.vue';
    import { fetchList } from '@/api/crm/customer';
    import { fetchList as teamList } from '@/api/crm/marketemployee';
    import { fetchList as address } from '@/api/crm/customeraddress'; //地址
    import { addOrder } from '@/api/crm/salesorder';
    import goodsRecord from './components/goodsRecord.vue';
    import goodsTable from './components/goodsTable.vue';
    import selectCustomerForm from '@/components/crm/select_customer_form';
    function data() {
        return {
            request: new Request(),
            customerRules: rules.customerRules,
            orderDetailRules: rules.orderDetailRules,
            disabled: true,
            customerOrder: this.customerOrderInfo(),
            orderList: this.orderListInfo(),
            promotionList: [],
            selectedRowIndex: '',
            teamList:[],
            addressList:[],
            // 选择标签
            dialogVisible: false,
            printDialogVisible: false,
            printTitle: {},
            printTable: [],
            orderInfo:{},
            // 文本域
            orderText: '',
            orderTextVisible: false,
            giftList:[]
        };
    }

    export default {
        data: data,
        computed: {
        },
        components: {
            goodsList,
            goodsRecord,
            goodsTable,
            selectCustomerForm,
            // , printOrder
        },
        mounted() {
            this.fetchBuyerList()
        },
        methods: {
            /**
             * 页面请求
             */
            async getGoodsList(params) {
                params.pageSize = 20;
                params.buyerId = this.customerOrder.buyerId;
                let res = await this.request.getGoodsList(params);
                if(res.code === 200) return res.ext.list;
                this.$message.warning('商品列表获取错误', res.msg);
                return [];
            },
            async handleSelectCustomer(customerObj) {
                if(this.customerOrder.customerSn === customerObj.customerSn) return;
                this.$set(this.customerOrder, 'customerAddressId', '');
                this.$set(this.customerOrder, 'customerSn', customerObj.customerSn);
                this.$set(this.customerOrder, 'customerName', customerObj.customerName);
                this.changeAddress(customerObj.customerSn);
            },
            changeTable(data, type) {
                switch(type) {
                case 1:
                    this.orderList = data;
                    break;
                case 2:
                    this.promotionList = data;
                    break;
                case 3:
                    this.giftList = data;
                    break;
                default:
                    break;
                }
                this.countPrice();
            },
            // 计算优惠价格
            countCouponAmount() {
                let couponAmount = this.getTotalAmount() - this.customerOrder.totalAmount;
                this.$set(this.customerOrder, 'couponAmount', couponAmount);
            },
            countPrice() {
                this.$set(this.customerOrder, 'totalAmount', this.getTotalAmount());
                this.countCouponAmount();
            },
            getTotalAmount() {
                let totalAmount = 0;
                let tableData = [].concat(this.orderList).concat(this.promotionList);
                tableData.map(item => {
                    totalAmount += parseFloat(item.goodsNum*item.buyPrice);
                })
                this.$set(this.customerOrder, 'goodsTotalAmount', totalAmount);
                totalAmount += this.customerOrder.otherAmount;
                return totalAmount;
            },
            async remoteStaffList(name) {
                let query = {};
                if(name) query.name = name;
                let res = await teamList(Object.assign(query, {current: 1, size: 50}));
                this.teamList = res.data.data.records;
            },
            fetchBuyerList() {
              teamList({current: 1, size: 100}).then(response => {
                this.teamList = response.data.data.records
              })
            },
            changeAddress(value){
              address({current: 1, size: 1000,customerSn:value}).then(response => {
                this.addressList = response.data.data.records
              })
              this.disabled = false;
            },
            addGoods(type) {
                switch(type) {
                case 1:
                    this.orderList.push(this.orderListInfo()[0]);
                    break;
                case 2:
                    this.promotionList.push(this.orderListInfo()[0]);
                    break;
                case 3:
                    this.giftList.push(this.orderListInfo()[0]);
                default:
                    break;
                }
            },
            async goodsSubmit(goodsText, type) {
                if(!goodsText) return this.$message.warning("请填写订单内容");
                let regex = /[\u3400-\u4DB5\u4E00-\u9FEA\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29\u{20000}-\u{2A6D6}\u{2A700}-\u{2B734}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}]+[0-9]+[\u3400-\u4DB5\u4E00-\u9FEA\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29\u{20000}-\u{2A6D6}\u{2A700}-\u{2B734}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}]/ug;
                let goodsList = goodsText.match(regex);
                if(!goodsList) return this.$message.warning("请填写订单内容");
                let regexName = /[\u3400-\u4DB5\u4E00-\u9FEA\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29\u{20000}-\u{2A6D6}\u{2A700}-\u{2B734}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}]+/u;
                let regexNum = /[0-9]+/;
                // 新增商品加入采购列表
                goodsList.forEach(async item =>{
                    let name = item.match(regexName);
                    let num = item.match(regexNum);
                    if(name && num){
                        name = name[0];
                        num = num[0];
                        let info = {
                            goodsId: '',
                            goodsImg: '',
                            goodsName : name,
                            goodsNum : num,
                            goodsModel: '',
                            purchasePrice: '',
                            buyPrice: '',
                            unit: '',
                            remarks: '',
                            loading: false,
                            goodsList: [],
                            goodsModelList: [],
                            salesGoodsType: type
                        }
                        let res = await this.getGoodsList({goodsName: name});
                        if(res.length > 0) {
                            info.goodsList = res;
                            info.goodsName = res[0].id;
                            info.goodsModelList = res[0].goodsModelList;
                            info.goodsId = res[0].goodsModelList[0].id;
                            info.buyPrice = res[0].goodsModelList[0].modelPrice;
                        } 
                        this.pushList(info, type);
                        this.countPrice();
                    }
                });
            },
            pushList(obj, type) {
                switch(type) {
                case 1:
                    this.orderList.push(obj);
                    break;
                case 2:
                    this.promotionList.push(obj);
                    break;
                case 3:
                    this.giftList.push(obj);
                    break;
                default:
                    break;
                }
            },

            resetForm() {
                this.disabled = true;
                this.customerOrder = this.customerOrderInfo();
            },
            submitBuyOrder() {
                const allGoodsList = [].concat(this.orderList).concat(this.promotionList).concat(this.giftList);
                this.$confirm("您现在已经完成了" + allGoodsList.length + "个商品的录入,确认下单？").then(res => {
                    let order = this.customerOrder
                    let detailList = [];
                    allGoodsList.map(item => {
                        if(!item.goodsName) return this.$message.warning("请输入数量");
                        if([1, 2].includes(item.salesGoodsType) && !item.buyPrice) return this.$message.warning("请输入价格");
                        detailList.push({
                            goodsModelId: item.goodsId,
                            salesGoodsType: item.salesGoodsType,
                            goodsNum: item.goodsNum,
                            dealPrice: item.buyPrice,
                            remarks: item.remarks
                        })
                    })
                    
                    order.detailList = detailList;
                    addOrder(order).then(res => {
                        let msg = '订单号: ' + res.data.data.salesOrderSn
                        this.$alert(msg, '提交成功', {
                            confirmButtonText: '确定'
                        })
                    }).then(res => {
                        let info = this.customerOrderInfo();
                        info.deliveryDate = order.deliveryDate;
                        this.customerOrder = info;
                        this.disabled = true;
                        this.orderList = this.orderListInfo();
                        this.orderTextVisible = false;
                        this.giftList = [];
                    })
                })
            },
            tomorrow() {
                return this.$utils.getDiffDate(1);
            },
            customerOrderInfo() {
                return {
                  otherAmount: 0,
                  couponAmount: 0,
                  customerSn: '',
                  salesType: '1',
                  employeeId: '',
                  customerAddressId: '',
                  totalAmount: 0,
                  remarks: '',
                  deliveryDate: this.tomorrow(),
                };
            },
            orderListInfo(){
                return [{
                  goodsModelId: '',
                  salesGoodsType: '',
                  goodsNum: '',
                  buyPrice: '',
                  remarks: '',
                }];
            },
        }
    };

</script>

<style scoped lang="scss">
    .page-wrap {
        height: 100%;

        .title {
            padding: 10px;
        }
    }

    .buyer-info {
        font-size: 16px;
    }

</style>
